package com.xkh.rocketmq.service;

import cn.hutool.core.util.IdUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.MessageQueueSelector;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.common.message.MessageQueue;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
@Slf4j
public class RocketMQService {

    @Resource
    private DefaultMQProducer defaultProducer;

    public boolean test1(String userId) {
        try {
            Message msg = new Message("Topic-1", "test1", IdUtil.simpleUUID(), (userId).getBytes());
            defaultProducer.send(msg);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("MQ-test1:", e);
            return false;
        }
        return true;
    }

    public boolean test2(String userId) {
        try {

            Message msg = new Message("Topic-2", "test2", IdUtil.simpleUUID(), (userId).getBytes());
            defaultProducer.send(msg);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("MQ-test2:", e);
            return false;
        }
        return true;
    }

    /**
     * 默认一个topic有4个队列 下标0-3
     *
     */
    public boolean test3(Long orderId,String content) {
        try {

            Message msg = new Message("Topic-3", "test3", "key:"+orderId, content.getBytes());
            defaultProducer.send(msg,(list,message,o)->{
                Integer id = (int) (orderId % list.size());
                System.out.println("队列:"+id);
                 return list.get(id);
            },1000);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("MQ-test3:", e);
            return false;
        }
        return true;
    }
}
